#!/bin/sh
#
# /etc/init.d/jenkins
# init script for a jenkins slave.
#
# chkconfig: 345 90 60
# description: jenkins slave
#

RETVAL=0

NAME=`basename "$0"`
JENKINS_CONFIG=/etc/sysconfig/$NAME
LOCK_FILE=/var/lock/$NAME
JAVA=/usr/bin/java
PIDFILE=/var/run/jenkins/$NAME.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Read config
[ -f "$JENKINS_CONFIG" ] && . "$JENKINS_CONFIG"

# Add scl-specific path as well as regular path.
# We add /usr/local/bin since that's where ccache symlinks live
JENKINS_PATH="/usr/local/bin:$JENKINS_PATH:$PATH"

# Replace potentially double colons since they add cwd
JENKINS_PATH="${JENKINS_PATH//::/:}"

slave_start() {
  echo Starting $NAME...

  mkdir `dirname $PIDFILE` > /dev/null 2>&1 || true
  chown $JENKINS_SLAVE_USER `dirname $PIDFILE`

  runuser -m -l $JENKINS_SLAVE_USER -c "$JENKINS_ENV PATH=$JENKINS_PATH $JAVA \
    -jar $JENKINS_SLAVE_JAR $JENKINS_SLAVE_ARGS > $JENKINS_SLAVE_LOG 2>&1 &"
  pgrep -f -u $JENKINS_SLAVE_USER $JENKINS_SECRET > $PIDFILE
  RETVAL=$?
  [ $RETVAL -eq 0 ] && touch $LOCK_FILE
}

slave_stop() {
  echo Stopping $NAME...
  pid=`cat $PIDFILE`

  killproc -p $PIDFILE

  # Wait until the monitor exits
  while (checkpid $pid)
  do
      usleep 100000
  done

  RETVAL=$?
  [ $RETVAL -eq 0 ] && rm -f $LOCK_FILE
}

slave_restart() {
  echo Restarting $NAME...
  slave_stop
  slave_start

  RETVAL=$?
  [ $RETVAL -eq 0 ] && touch $LOCK_FILE
}

slave_status() {
  status -p $PIDFILE $NAME
  RETVAL=$?
}

case "$1" in
  start)
    slave_start
    ;;
  stop)
    slave_stop
    ;;
  restart)
    slave_restart
    ;;
  status)
    slave_status
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|status}"
    exit 1
    ;;
esac

exit $RETVAL
